package org.carabiner.infinitest.swingui;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JProgressBar;
import javax.swing.Timer;

class CustomProgressBar extends JProgressBar implements ActionListener
{
  private Timer timer;
  private ColorAnimator animator;

  public CustomProgressBar(ColorAnimator colorAnimator)
  {
    animator = colorAnimator;
    setBorder(BorderFactory.createLineBorder(getBackground(), 2));
    setBorderPainted(true);
    timer = new Timer(animator.getAnimationRate(), this);
    timer.start();
  }
  
  @Override
  protected void paintComponent(Graphics g)
  {
    Graphics2D g2 = (Graphics2D) g.create();
    drawProgressBar(g2);
    drawText(g2);
    g2.dispose();
  }

  private void drawText(Graphics2D g2)
  {
    g2.setColor(Color.BLACK);
    g2.drawString(getString(), 10, 15);
  }

  private void drawProgressBar(Graphics2D g2)
  {
    Rectangle rectangle = new Rectangle(0, 0, (int) (getPercentComplete() * getSize().getWidth()), getSize().height);
    g2.setColor(animator.shiftColorOnAnimationTick(getForeground()));
    Insets insets = getBorder().getBorderInsets(this);
    int insetWidth = (insets.left + insets.right);
    int insetHeight = (insets.top + insets.bottom);
    g2.fillRoundRect(insets.left, insets.top, rectangle.width - insetWidth, rectangle.height - insetHeight, 15, 15);
  }

  public void actionPerformed(ActionEvent e)
  {
    repaint();
    animator.tick();
  }
}
